package com.berwin.syncer.monitor;

import com.berwin.syncer.listener.ClipboardListener;
import com.berwin.syncer.utils.ClipboardUtility;

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;

/**
 * 剪贴板监控器
 * 负责对剪贴板文本的监控和操作
 * 由于监控需要一个对象作为ClipboardOwner，故不能用静态类
 */
public class SystemClipboardMonitor implements ClipboardOwner, Runnable {

    private ClipboardListener listener;
    private String lastClipboard = ClipboardUtility.getSysClipboardText();
    private boolean isRunning;

    private int interval = 1;

    public SystemClipboardMonitor(ClipboardListener listener) {
        this.listener = listener;
        this.lastClipboard = ClipboardUtility.getSysClipboardText();
    }

    public void start(int interval) {
        this.interval = interval;
        this.isRunning = true;
        new Thread(this).start();
    }

    public void stop() {
        this.isRunning = false;
    }

    /**********************************************
     * 如果剪贴板的内容改变，则系统自动调用此方法 *
     **********************************************
     */
    @Override
    public void lostOwnership(Clipboard clipboard, Transferable contents) {
    }

    @Override
    public void run() {
        while (this.isRunning) {
            try {
                Thread.sleep(1000 * interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String text = ClipboardUtility.getSysClipboardText();
            if (!text.equals(lastClipboard)) {
                lastClipboard = text;
                this.listener.onClipboardChanged(text);
            }
        }

    }

    public String getLastClipboard() {
        return lastClipboard;
    }

    public void setLastClipboard(String lastClipboard) {
        this.lastClipboard = lastClipboard;
    }
}
